-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve command option types #1356
Conversation
Related: #1245 |
Very cool, thanks for sharing! There will be lots of challenges to making the inferred typing accurate. There is also:
Removing the option-keys from the program type when |
Wrap option in partial since it may be omitted. requiredOption is guaranteed to get the value, so don't wrap it in partial.
Another challenge is the |
For interest, I did some quick research on whether possible to support multiple versions of TypeScript |
This PR is not active, but has demonstrated some pretty interesting possibilities. It will be hard to do an accurate representation of the options due to the flexible ways they are described and added, and not easily cover all use cases (e.g. the typings will not be trivially available for parameter of an action handler). But deduced typings may be looked at again in future. Thank you for your contributions. |
For some experimental strong inferred typing see: https://github.com/commander-js/extra-typings |
Pull Request
Use TypeScript's new template literal types to improve the command option types. This allows the option flags to be parsed at the type level, giving accurate types to the resulting program object instead of falling back on
{ [key: string]: any }
.--no-
prefixed optionsProblem
Currently there is no real type checking for options, so I might access an option that doesn't exist.
Solution
TypeScript recently added template literal types, allowing types to match patterns in strings. This allows us to parse the option name, and whether it has a required/optional value. Note that this feature is not released yet, but could be released with TypeScript 4.1.0.
See a working example on the typescript playground. Scroll to the bottom and hover the
program
variable.TypeScript will fail to compile if the option flags are not in the right format.
To get the right behavior, the result of chaining off of
commander
needs to be assigned to a new variable, since the type is built up as a result of the chaining.ChangeLog